package viettravel.DTO;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import viettravel.common.Constants;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseConnection extends SQLiteOpenHelper {

	private Context mContext;
	private static String mFolderPath = Constants.CLIENT_DATA_FOLDER_PATH;
	private static String mDBName = Constants.CLIENT_DATA_NAME;
	private static String mDBPath = mFolderPath + mDBName;
	private static int mDataVersion = Constants.CLIENT_VERSION;

	private SQLiteDatabase mViettravelDB;

	public DatabaseConnection(Context _context) {
		super(_context, mDBName, null, mDataVersion);
		mContext = _context;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub

	}

	public void createDataBase() throws IOException {
		boolean dbExist = checkDataBase();
		if (!dbExist) {
			this.getReadableDatabase();
			this.getWritableDatabase();
			try {
				copyDataBase();
			} catch (IOException e) {
				Log.e(Constants.TAG, "Error coppy database");
			}
		}
	}

	private boolean checkDataBase() {
		/*
		 * File dbFile = new File(mDBPath); return dbFile.exists();
		 */
		SQLiteDatabase checkDB = null;
		try {
			String databasePath = mDBPath;
			checkDB = SQLiteDatabase.openDatabase(databasePath, null,
					SQLiteDatabase.OPEN_READWRITE);
		} catch (SQLiteException e) {
			Log.e(Constants.TAG, "Database exits");
		}
		if (checkDB != null)
			checkDB.close();
		return checkDB != null ? true : false;
	}

	private void copyDataBase() throws IOException {
		InputStream input = mContext.getAssets().open(mDBName);
		String databasePath = mDBPath;
		OutputStream output = new FileOutputStream(databasePath);
		byte[] buffer = new byte[1024];
		int length;
		while ((length = input.read(buffer)) > 0) {
			output.write(buffer, 0, length);
		}
		output.flush();
		output.close();
		input.close();
	}

	public void openDataBase() {
		// Open the database
		String databasePath = mDBPath;
		try {
			mViettravelDB = SQLiteDatabase.openDatabase(databasePath, null,
					SQLiteDatabase.OPEN_READWRITE
							| SQLiteDatabase.NO_LOCALIZED_COLLATORS);
		} catch (Exception e) {
			Log.e(Constants.TAG, "Error open database");
		}
	}

	public SQLiteDatabase getDB() {
		return mViettravelDB;
	}

	@Override
	public synchronized void close() {
		if (mViettravelDB != null)
			mViettravelDB.close();
		super.close();
	}
}
